package com.photoeditor.demo.ui.activity.subscribe;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.billing.base.SimpleBillingUpdateListener;
import com.billing.base.SkuWithType;
import com.billing.base.internal.SkuDetailsCacheManager;
import com.common.base.ComponentContext;
import com.common.base.utils.TimeConstant;
import com.common.commercialize.sdk.CommercializeSDK;
import com.common.commercialize.utils.TaskRunnable;
import com.photoeditor.R;
import com.photoeditor.demo.ad.InAppAdProvider;
import com.photoeditor.demo.model.event.SubscribeFinishEvent;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.manager.VipStatisticUtil;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.HomeActivity;
import com.photoeditor.demo.ui.adapter.home.UltraPagerAdapter;
import com.photoeditor.demo.ui.adapter.home.UltraPagerAdapter1;
import com.photoeditor.demo.ui.widget.RippleConstraintLayout;
import com.photoeditor.demo.util.AndroidDevice;
import com.photoeditor.demo.util.AppFrontBackHelper;
import com.photoeditor.demo.util.DisplayUtils;
import com.photoeditor.demo.util.FontUtil;
import com.tmall.ultraviewpager.UltraViewPager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.photoeditor.demo.app.Global.PRIVACY_URL;
import static com.photoeditor.demo.app.Global.REFUND_URL;
import static com.photoeditor.demo.statistics.StatisticsConstant.ENTRANCE_VALUE_OPEN_APP;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_B;
import static com.photoeditor.demo.util.CheckPhoneHasBottomBarUtils.hasNavBar;


/**
 * Created by Lai on 2018/10/25 0025.
 */
public class SubscribeActivity extends BaseSubscribeActivity {

    public static boolean sSubscribeShow = false;

    @Bind(R.id.ultraViewPager)
    UltraViewPager ultraViewPager;
    @Bind(R.id.img_check_first)
    ImageView mImgCheckFirst;
    @Bind(R.id.tv_vip_first_title)
    TextView mTvFirstTitle;
    @Bind(R.id.tv_vip_first_tip)
    TextView mTvFirstTip;
    @Bind(R.id.img_check_second)
    ImageView mImgCheckSecond;
    @Bind(R.id.tv_vip_second_tip_title)
    TextView mTvSecondTipTitle;
    @Bind(R.id.tv_vip_second_tip)
    TextView mTvSecondTip;
    @Bind(R.id.tv_vip_bottom_tip)
    TextView mTvBottomTip;
    @Bind(R.id.iv_vip_btn_anim)
    ImageView mIvBtnAnim;
    @Bind(R.id.cl_vip_first)
    RippleConstraintLayout mFirstLayout;
    @Bind(R.id.cl_vip_second)
    RippleConstraintLayout mSecondLayout;
    @Bind(R.id.cancel)
    TextView mCancelTextView;

    private AnimationDrawable mDrawable;
    private int payColor;

    private String mPricePerMonMonthly;
    //    private String mPricePerMonYearly;
    private String mPriceYearly;
    private String mFreeDaysMonthly;
    private String mFreeDaysYearly;

    private int mSkuType;

    private boolean mHasShowRetain;

    private boolean mStartMain;
    private boolean mHasLoadPrice;

    private int mCount;
    private List<View> mIndicators = new ArrayList<>();
    private int mLastPosition = 0;

    private boolean mFirstClick = true;

    private InAppAdProvider mInAppAdProvider;
    private boolean mIsNewUser;

    private SimpleBillingUpdateListener mDetailsResponseListener = new SimpleBillingUpdateListener() {

        @Override
        public void onSkuDetailsResponse(int i, List<SkuDetails> list) {
            if (list == null || list.isEmpty()) {
                return;
            }
            mHasLoadPrice = true;
            String skuMonth = SkuManager.getSkuInfoLast(SkuManager.TYPE_MONTHLY);
            String skuYear = SkuManager.getSkuInfoLast(SkuManager.TYPE_YEARLY);

            for (SkuDetails skuDetails : list) {
                if (TextUtils.equals(skuDetails.getSku(), skuMonth)) {
                    mPricePerMonMonthly = skuDetails.getPrice();
                } else if (TextUtils.equals(skuDetails.getSku(), skuYear)) {
                    mPriceYearly = skuDetails.getPrice();
                    /*BigDecimal b1 = new BigDecimal(Float.toString(skuDetails.getPriceAmountMicros() / 1000000.0f));
                    BigDecimal b2 = new BigDecimal(12);
                    BigDecimal divide = b1.divide(b2, 2, RoundingMode.HALF_UP);
                    mPricePerMonYearly = skuDetails.getPriceCurrencyCode() + " " + divide.toString();*/
                }
            }
            initPriceView();
        }
    };

    public static void startActivity(Activity activity, String entrance, SVipController.OnSubscribeCloseListener listener, int requestCode, boolean startMain) {
        Intent intent = new Intent(ComponentContext.getContext(), SubscribeActivity.class);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE, entrance);
        intent.putExtra(EXTRA_TYPE,"B");
        intent.putExtra(EXTRA_START_MAIN, startMain);
        activity.startActivityForResult(intent, requestCode);
        sOnSubscribeCloseListener = listener;
        sSubscribeShow = true;
    }

    public static void startActivity(String entrance, SVipController.OnSubscribeCloseListener listener) {
        Intent intent = new Intent(ComponentContext.getContext(), SubscribeActivity.class);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE, entrance);
        intent.putExtra(EXTRA_TYPE,"B");
        ComponentContext.getContext().startActivity(intent);
        sOnSubscribeCloseListener = listener;
        sSubscribeShow = true;
    }

    @Override
    protected void initData() {
        super.initData();
//        EventBus.getDefault().register(this);
        mStartMain = getIntent().getBooleanExtra(EXTRA_START_MAIN, false);
        mHasShowRetain = false;


        mSkuType = SVipStrategyManager.getInstance().getFirstSubscribeType();

        mFreeDaysMonthly = SkuManager.getVipFreeDays(SkuManager.TYPE_MONTHLY);
        mFreeDaysYearly = SkuManager.getVipFreeDays(SkuManager.TYPE_YEARLY);

        String skuMonth = SkuManager.getSkuInfoLast(SkuManager.TYPE_MONTHLY);
        if (!TextUtils.isEmpty(skuMonth)) {
            SkuWithType skuWithType = new SkuWithType(skuMonth, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType, mDetailsResponseListener);
            if (cacheSkuDetails != null) {
                String price = cacheSkuDetails.getPrice();
                if (!TextUtils.isEmpty(price)) {
                    mHasLoadPrice = true;
                    mPricePerMonMonthly = price;
                }
            }
        }

        String skuYear = SkuManager.getSkuInfoLast(SkuManager.TYPE_YEARLY);
        if (!TextUtils.isEmpty(skuYear)) {
            SkuWithType skuWithType = new SkuWithType(skuYear, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType, mDetailsResponseListener);
            if (cacheSkuDetails != null) {
                String price = cacheSkuDetails.getPrice();
                if (!TextUtils.isEmpty(price)) {
                    mHasLoadPrice = true;
                    mPriceYearly = price;
                }
                /*BigDecimal b1 = new BigDecimal(Float.toString(cacheSkuDetails.getPriceAmountMicros() / 1000000.0f));
                BigDecimal b2 = new BigDecimal(12);
                BigDecimal divide = b1.divide(b2, 2, RoundingMode.HALF_UP);
                mPricePerMonYearly = cacheSkuDetails.getPriceCurrencyCode() + " " + divide.toString();*/
            }
        }

        mIsNewUser = SpUtils.obtain().getBoolean("st_n_op", true);
        if (mStartMain && !mIsNewUser) {
            mInAppAdProvider = new InAppAdProvider(this);
            mInAppAdProvider.loadAd();
        }
        initPriceView();
    }

//    private void setPrivacyUnderlineBuyUser(String privacyFull) {
//        String privacy = getResources().getString(R.string.vip_privacy);
//        int privacySIndex = privacyFull.indexOf(privacy);
//        int privacyEIndex = privacySIndex + privacy.length();
//        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
//        try {
//            builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//            builder.setSpan(new ClickableSpan() {
//                @Override
//                public void onClick(View widget) {
//                    AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
//                }
//
//            }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        mTvBottomTip.setHighlightColor(getResources().getColor(R.color.transparent));
//        mTvBottomTip.setLinkTextColor(mTvBottomTip.getCurrentTextColor());
//        mTvBottomTip.setMovementMethod(LinkMovementMethod.getInstance());
//        mTvBottomTip.setText(builder);
//    }

    private void setPrivacyUnderline(String privacyFull) {
        String privacy = getResources().getString(R.string.vip_privacy);
        int privacySIndex = privacyFull.indexOf(privacy);
        int privacyEIndex = privacySIndex + privacy.length();
        String refund = getResources().getString(R.string.vip_cancel_refund);
        int refundSIndex = privacyFull.indexOf(refund);
        int refundEIndex = refundSIndex + refund.length();
        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
        try {
            builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
                }
            }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new UnderlineSpan(), refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AndroidDevice.startWebView(ComponentContext.getContext(), REFUND_URL);
                }
            }, refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvBottomTip.setHighlightColor(getResources().getColor(R.color.transparent));
        //mTvBottomTip.setLinkTextColor(mTvBottomTip.getCurrentTextColor());
        payColor=SpUtils.obtain().getInt("payColor", 0xff3a3a87);
        mTvBottomTip.setLinkTextColor(payColor);
        mTvBottomTip.setMovementMethod(LinkMovementMethod.getInstance());
        mTvBottomTip.setText(builder);
    }

    @Override
    protected void initView() {
        initViewPager();

        ((RippleConstraintLayout) findViewById(R.id.cl_vip_first)).setMask(R.drawable.bg_subscribe_mask);
        ((RippleConstraintLayout) findViewById(R.id.cl_vip_second)).setMask(R.drawable.bg_subscribe_mask);
        ((RippleConstraintLayout) findViewById(R.id.layout_vip_continue)).setMask(R.drawable.bg_subscribe_mask);
        mDrawable = (AnimationDrawable) mIvBtnAnim.getDrawable();
        mDrawable.start();

        initFirstEnter();
    }

    @Override
    protected int getContentLayoutId() {
        /*int height = getRealScreenHeight();
        int width = DeviceUtils.getScreenWidthPx();
        float ratio = (float) height / width;
        DLog.d("screenLog", "height: " + height + " width: " + width);
        if (ratio >= 2 && ratio <= 2.05) {
            //2:1手机适配
            return R.layout.activity_subscribe_a_1080_2160;
        } else if (ratio > 2.05) {
            //19:9手机适配
            return R.layout.activity_subscribe_a_1080_2280;
        } else {*/
        //正常16:9手机
        return R.layout.activity_subscribe;
//        }
    }

    private void initPriceView() {
        if (TextUtils.isEmpty(mPricePerMonMonthly)) {
            mTvFirstTitle.setText(String.format(getResources().getString(R.string.vip_palm_full_one_month),
                    getResources().getText(R.string.vip_price_b_month)));
            mTvFirstTip.setText(String.format(getResources().getString(R.string.vip_monthly_tips),
                    getResources().getText(R.string.vip_price_b_month)));
        } else {
            mTvFirstTitle.setText(String.format(getResources().getString(R.string.vip_palm_full_one_month), mPricePerMonMonthly));
            mTvFirstTip.setText(String.format(getResources().getString(R.string.vip_monthly_tips), mPricePerMonMonthly));
        }

        mCancelTextView.setText(String.format(getResources().getString(R.string.vip_feature_tip),
                mFreeDaysMonthly));

        if (TextUtils.isEmpty(mPriceYearly)) {
            mTvSecondTip.setText(String.format(getResources().getString(R.string.vip_yearly_tips),
                    getResources().getText(R.string.vip_price_b_year)));
        } else {
            mTvSecondTip.setText(String.format(getResources().getString(R.string.vip_yearly_tips), mPriceYearly));
        }

        if (mSkuType == SkuManager.TYPE_MONTHLY) {
//            if (BuyUserManager.getInstance().isBuyUser()) {
//                mTvBottomTip.setGravity(Gravity.CENTER);
//                setPrivacyUnderlineBuyUser(getResources().getString(R.string.vip_privacy_buy_user));
//            } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPricePerMonMonthly) ?
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly,
                            getResources().getText(R.string.vip_price_b_month)) :
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly, mPricePerMonMonthly));
//            }
            setCheckStatus(true);
        } else {
//            if (BuyUserManager.getInstance().isBuyUser()) {
//                mTvBottomTip.setGravity(Gravity.CENTER);
//                setPrivacyUnderlineBuyUser(getResources().getString(R.string.vip_privacy_buy_user));
//            } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPriceYearly) ?
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly,
                            getResources().getText(R.string.vip_price_b_year)) :
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly, mPriceYearly));
//            }
            setCheckStatus(false);
        }

        if (SVipStrategyManager.getInstance().canShowBottomTipText(SVipConstant.VIP_ENTRANCE_IN_APP)) {
            mTvBottomTip.setVisibility(View.VISIBLE);
        } else {
            mTvBottomTip.setVisibility(View.GONE);
        }
    }

    private void initViewPager() {

        ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
//initialize UltraPagerAdapter，and add child view to UltraViewPager
        UltraPagerAdapter1 adapter = new UltraPagerAdapter1(false, false);
        ultraViewPager.setAdapter(adapter);
//initialize built-in indicator
        ultraViewPager.initIndicator();
        ultraViewPager.getIndicator().setMargin(0, 0, 0, DisplayUtils.dp2px(50));
//set style of indicators
        ultraViewPager.getIndicator()
                .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                .setFocusColor(Color.WHITE)
                .setNormalColor(Color.parseColor("#66ffffff"))
                .setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics()));
//set the alignment
        ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
//construct built-in indicator, and add it to  UltraViewPager
        ultraViewPager.getIndicator().build();

//set an infinite loop
        ultraViewPager.setInfiniteLoop(true);
//enable auto-scroll mode
        ultraViewPager.setAutoScroll(2500);


        final ViewPager viewPager = ultraViewPager.getViewPager();
//        setViewPagerScroller(viewPager);
        //viewPager点击事件
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            int touchFlag = 0;
            float x = 0, y = 0;
            ViewConfiguration configuration = ViewConfiguration.get(SubscribeActivity.this);
            int mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        touchFlag = 0;
                        x = event.getX();
                        y = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float xDiff = Math.abs(event.getX() - x);
                        float yDiff = Math.abs(event.getY() - y);
                        if (xDiff < mTouchSlop && xDiff >= yDiff)
                            touchFlag = 0;
                        else
                            touchFlag = -1;
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });
    }

    private boolean firstEnter = false;

    private void initFirstEnter() {
        if (SpUtils.obtain().getBoolean("first_enter", true)) {
            SpUtils.obtain().save("first_enter", false);
            firstEnter = true;
        }
        showVipClose();
    }

    private void showVipClose() {
        if (!firstEnter) {
            findViewById(R.id.iv_vip_close).setVisibility(View.VISIBLE);
            return;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(SubscribeActivity.this, R.anim.activity_open_enter);
                findViewById(R.id.iv_vip_close).setVisibility(View.VISIBLE);
                findViewById(R.id.iv_vip_close).startAnimation(animation);
            }
        }, 2000);
    }


    @Override
    protected boolean isPurchaseSuccess(List<Purchase> purchases) {
        boolean isMonthlyVip = false;
        boolean isYearlyVip = false;
        if (purchases != null) {
            for (Purchase purchase : purchases) {
                String sku;
                if (purchase != null && (sku = purchase.getSku()) != null) {
                    String[] monthlySkus = SkuManager.getSkuInfo(SkuManager.TYPE_MONTHLY);
                    String[] yearlySkus = SkuManager.getSkuInfo(SkuManager.TYPE_YEARLY);
                    for (String monthlySku : monthlySkus) {
                        if (TextUtils.equals(sku, monthlySku)) {
                            isMonthlyVip = true;
                        }
                    }
                    if (!isMonthlyVip) {
                        for (String yearlySku : yearlySkus) {
                            if (TextUtils.equals(sku, yearlySku)) {
                                isYearlyVip = true;
                            }
                        }
                    }
                }
            }
        }

        return isMonthlyVip || isYearlyVip;
    }

    @Override
    protected void onPurchaseSuccess() {

    }

    @Override
    protected void onPurchaseFailUserCancel() {
        super.onPurchaseFailUserCancel();
        if (!TextUtils.equals(mStatisticsEntrance, ENTRANCE_VALUE_OPEN_APP)) {

        } else if (mHasShowRetain || !SVipController.showRetainDialog(this, mStatisticsEntrance, 111)) {

        } else {
            mHasShowRetain = true;
            mVisible = false;
        }
    }

    /**
     * 页面
     *
     * @return
     */
    @Override
    public String getStatisticPageStr() {
        //        if (mSkuType == SkuManager.TYPE_MONTHLY) {
        //            return StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_PAGE_ACTIVITY_MONTH;
        //        } else {
        //            return StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_PAGE_ACTIVITY_NEW;
        //        }
        return StatisticsConstant.EVENT_MAIN_SUB;
    }

    @Override
    public String getSubscribeTypeStr() {
        return MAIN_PAGE_TYPE_B;
    }

    @Override
    public boolean statisticSubPageShowAndClick() {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(hasNavBar(this)){//有虚拟键
            hideBottomUIMenu();
        }
        if (mDrawable != null) {
            mDrawable.start();
        }
        if (!SVipStrategyManager.hasStatisticReopen()
                && System.currentTimeMillis() - CommercializeSDK.getInstance().getFirstInstallTime() < TimeConstant.ONE_DAY
                && SVipStrategyManager.hasLeaveFromSub()
                && !SVipStrategyManager.hasShowMainAfterSub()) {
            //在首次展示订阅页面后未进入首页即退出应用，在当天再次进入应用的用户
            SVipStrategyManager.setHasStatisticReopen();
            VipStatisticUtil.statisticLeaveIn();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDrawable != null) {
            mDrawable.stop();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (AppFrontBackHelper.getInstant().isAppBackground()) {
            SVipStrategyManager.setHasLeaveFromSub();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubscribeFinishEvent(SubscribeFinishEvent event) {
        onBack();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111 && resultCode == RESULT_OK) {
            postDelayed(new Runnable() {
                @Override
                public void run() {

                }
            }, 250);

        }
    }

    private void onBack() {
        TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
            @Override
            public void run() {
                finish();
                statisticBack(false);
            }
        };
        if (mStartMain && !mIsNewUser) {
            mInAppAdProvider.showAd(taskRunnable);
        } else {
            taskRunnable.runSelfAdaptation();
        }
    }

    @Override
    public void onBackPressed() {
        if (SpUtils.obtain().getBoolean("first_enter", true)) {
            SpUtils.obtain().save("first_enter", false);
        } else {
            onBackClick();
            return;
        }
    }

    @OnClick(R.id.iv_vip_close)
    void onBackClick() {
        if (!TextUtils.equals(mStatisticsEntrance, ENTRANCE_VALUE_OPEN_APP)) {
            onBack();
        } else if (mHasShowRetain || !SVipController.showRetainDialog(this, mStatisticsEntrance, 111)) {
            onBack();
        } else {
            mHasShowRetain = true;
            mVisible = false;
            statisticCloseClick();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mHasShowRetain) {
            mVisible = false;
        }
    }

    void purchaseMonthly() {
        String[] normalSkus = SkuManager.getSkuInfo(SkuManager.TYPE_MONTHLY);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        subscribe(normalSkus[normalSkus.length - 1],
                StatisticsConstant.SUB_PACK_VALUE_MONTHLY);

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_BTN_CLICK,
                StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_MONTH,
                StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
                StatisticsConstant.KEY_AB_TYPE,StatisticsConstant.VALUE_B,
                StatisticsConstant.KEY_SKU,sku);
    }

    void purchaseYearly() {
        String[] normalSkus = SkuManager.getSkuInfo(SkuManager.TYPE_YEARLY);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        subscribe(normalSkus[normalSkus.length - 1],
                StatisticsConstant.SUB_PACK_VALUE_ANNUAL);

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_BTN_CLICK,
                StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_YEAR,
                StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
                StatisticsConstant.KEY_AB_TYPE,StatisticsConstant.VALUE_B,
                StatisticsConstant.KEY_SKU,sku);
    }

    @OnClick({R.id.layout_vip_continue})
    void onSubscribeClick() {
        if (mSkuType == SkuManager.TYPE_MONTHLY) {
            purchaseMonthly();
        } else {
            purchaseYearly();
        }
    }

    @OnClick(R.id.cl_vip_first)
    void onFirstBtnClick() {
        setCheckStatus(true);
        mSkuType = SkuManager.TYPE_MONTHLY;
//        onSubscribeClick();
    }

    @OnClick(R.id.cl_vip_second)
    void onSecondBtnClick() {
        setCheckStatus(false);
        mSkuType = SkuManager.TYPE_YEARLY;
//        onSubscribeClick();
    }

    private void setCheckStatus(boolean first) {
        mTvFirstTitle.setTextColor(getResources().getColor(first ? R.color.color_subscribe_btn_text_color : R.color.color_subscribe_btn_text_color_unsel));
        mTvFirstTitle.setTypeface(first ? FontUtil.CUSTOM_FONT_MEDIUM : Typeface.DEFAULT);
        mImgCheckFirst.setImageResource(first ? R.drawable.ic_radio_on : R.drawable.ic_radio_off);
        mFirstLayout.setBackground(getResources().getDrawable(first ? R.drawable.bg_subscribe_selected : R.drawable.bg_subscribe_normal));
        mTvFirstTip.setVisibility(first ? View.VISIBLE : View.GONE);

        mTvSecondTipTitle.setTextColor(getResources().getColor(!first ? R.color.color_subscribe_btn_text_color : R.color.color_subscribe_btn_text_color_unsel));
        mTvSecondTipTitle.setTypeface(!first ? FontUtil.CUSTOM_FONT_MEDIUM : Typeface.DEFAULT);
        mImgCheckSecond.setImageResource(!first ? R.drawable.ic_radio_on : R.drawable.ic_radio_off);
        mSecondLayout.setBackground(getResources().getDrawable(!first ? R.drawable.bg_subscribe_selected : R.drawable.bg_subscribe_normal));
        mTvSecondTip.setVisibility(!first ? View.VISIBLE : View.GONE);

        if (first) {
//            if (BuyUserManager.getInstance().isBuyUser()) {
//                mTvBottomTip.setGravity(Gravity.CENTER);
//                setPrivacyUnderlineBuyUser(getResources().getString(R.string.vip_privacy_buy_user));
//            } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPricePerMonMonthly) ?
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly,
                            getResources().getText(R.string.vip_price_b_month)) :
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly, mPricePerMonMonthly));
//            }
        } else {
//            if (BuyUserManager.getInstance().isBuyUser()) {
//                mTvBottomTip.setGravity(Gravity.CENTER);
//                setPrivacyUnderlineBuyUser(getResources().getString(R.string.vip_privacy_buy_user));
//            } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPriceYearly) ?
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly,
                            getResources().getText(R.string.vip_price_b_year)) :
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly, mPriceYearly));
//            }
        }
    }

    @Override
    protected void onDestroy() {
        sSubscribeShow = false;
        super.onDestroy();
        SkuDetailsCacheManager.getInstance().removeSkuDetailsResponseListeners(mDetailsResponseListener);
//        EventBus.getDefault().unregister(this);
        //        if (!mHasLoadPrice) {
        //            VipStatisticUtil.statistic(StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_NO_PRICE, getStatisticPageStr());
        //        }

        if (mStartMain && !mIsNewUser) {
            mInAppAdProvider.destroyAd();
        }
    }

    @Override
    public void finish() {
        checkToStartMain();
        setResult(RESULT_OK);
        super.finish();
    }

    private void checkToStartMain() {
        if (mStartMain) {
            Intent i = new Intent(this, HomeActivity.class);
            startActivity(i);
            overridePendingTransition(R.anim.activity_no_animation, R.anim.activity_close_exit);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK && firstEnter) {
            return false;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK && firstEnter) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}
